package com.cj.framework.security.filter;

import com.cj.ai.domain.WxLogin;
import com.cj.common.constant.CacheConstants;
import com.cj.common.core.domain.AjaxResult;
import com.cj.common.core.domain.R;
import com.cj.common.core.redis.RedisCache;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 小程序必须携带 openid
 * @author cc
 * @date 2024-08-21 15:32
 **/
@Component
public class MpAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/mp") && !requestURI.contains("/mp/login")){
            String authToken = request.getHeader("mp_token");
            // 判断是否有openid
            WxLogin cacheObject = redisCache.getCacheObject(CacheConstants.WX_LOGIN_PREFIX + authToken);
            if (cacheObject == null){
                // redis没有找到
                response.setContentType("application/json;charset=utf-8");
                String s = new ObjectMapper().writeValueAsString(AjaxResult.error(401, "请先登录"));
                response.getWriter().write(s);
            }else{

                // 前端做，，， 前端存令牌过期时间，，看是否过期，，这个过期时间可以小程序自己生成，也可以服务器返回
//                // 判断redis是否快过期，， 续期
//                long expire = redisCache.getExpire(CacheConstants.WX_LOGIN_PREFIX + authToken);
//                if (expire < 20){
//                    // 重新设置redis
//                    redisCache.setCacheObject(CacheConstants.WX_LOGIN_PREFIX + authToken,cacheObject,60, TimeUnit.MINUTES);
//                }

                // 过滤器往后走，， 其他不让
                filterChain.doFilter(request,response);
            }
        }else{


            // 其他请求不拦截
            filterChain.doFilter(request,response);

        }


    }
}
